package com.eden.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.eden.domain.Student;
import com.eden.listener.StudentListener;
import com.sun.deploy.net.HttpResponse;
import com.sun.deploy.net.URLEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ClassName: EasyController
 * Package: com.eden.controller
 * Description: todo
 * Date:  2020/10/18 16:26
 *
 * @Author: 李秉林
 */
@RestController
public class EasyController {
	
	@PostMapping("/ddd")
	public void get(MultipartFile file) {
		try {
			ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), Student.class, new StudentListener());
			ExcelReaderSheetBuilder sheet = read.sheet();
			sheet.doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@GetMapping("/get")
	public void f(HttpServletResponse response) {
		try {
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			// 防止中文乱码
			String fileName = URLEncoder.encode("测试", "UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
			
			List<Student> list = new ArrayList<Student>();
			for (int i = 0; i < 100; i++) {
				Student student = new Student();
				student.setAge(new CellData<Integer>(1));
				student.setBirthday(new Date());
				student.setName("aaa" + i);
				list.add(student);
			}
			ServletOutputStream outputStream = response.getOutputStream();
			ExcelWriterBuilder write = EasyExcel.write(outputStream, Student.class);
			ExcelWriterSheetBuilder sheet = write.sheet();
			sheet.doWrite(list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
